package com.baizhi.jishi.controller;

import com.baizhi.jishi.util.ValidationCodeUtils;
import org.patchca.service.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class ValidationCodeAction {
	@RequestMapping("/validateCode")
	public void validateCode(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		//调用工具方法获取验证码
		Captcha c = ValidationCodeUtils.getCaptcha();
		String validationCode = c.getChallenge();
//		System.out.println("validationCode = "+validationCode);
		HttpSession session = request.getSession();
		session.setAttribute("validationCode", validationCode);
		//BuffedImage类型对象代表一个图片
		BufferedImage bi = c.getImage();
		System.out.println();
		//设置响应类型
		response.setContentType("image/png");
		response.setHeader("cache", "no-cache");
		//将图片通过输出流，响应回浏览器
		OutputStream out = response.getOutputStream();
		//将图片bi以png格式使用out流输出
		ImageIO.write(bi, "png", out);
		
	}
}
